package com.ljh.cloudmusic.utils;
import com.ljh.cloudmusic.utils.JwtUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * @author: Themberfue
 * @date: 2025/3/15 11:06
 * @description:
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // TODO 获取 Authorization 头
        String token = request.getHeader("Authorization");

        // TODO 校验 Token
        if (token == null || !token.startsWith("Bearer ")) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 401 未授权
            return false;
        }

        // TODO 去掉 "Bearer " 部分
        token = token.substring(7);

        // TODO 验证 Token
        if (!JwtUtils.isTokenValid(token)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        // TODO 解析 Token 并将 username 存入请求作用域，方便后续使用
        request.setAttribute("username", JwtUtils.getUsernameFromToken(token));

        return true; // 继续执行请求
    }
}
